package dao

import (
	"server_cluster/http/model"
	"time"
)

// QueryAccountByUserName 通过tap第三方sdk的openid查询账号
func (d *Dao) QueryAccountByUserName(UserName string) (*model.DbAccount, error) {
	account := new(model.DbAccount)
	err := d.db.Where("username = ?", UserName).First(account).Error
	if err != nil {
		return nil, err
	}
	return account, nil
}

// InsertAccount 新增账号
func (d *Dao) InsertAccount(account *model.DbAccount) (int64, error) {
	account.CreateTime = time.Now()
	account.UpdateTime = time.Now()
	err := d.db.Create(account).Error
	if err != nil {
		return 0, err
	}
	return account.Uid, nil
}

// UpdateAccount 更新账号
func (d *Dao) UpdateAccount(account *model.DbAccount) error {
	account.UpdateTime = time.Now()
	err := d.db.Model(account).Updates(account).Error
	if err != nil {
		return err
	}
	return nil
}

func (d *Dao) CheckAccountToken4Internal(uid int64, token string) bool {
	account := new(model.DbAccount)
	err := d.db.Model(account).
		Where("id = ?", uid).
		Where("token = ?", token).
		First(&account).Error
	if err != nil {
		return false
	}
	if account.Uid == 0 || account.Uid != uid {
		return false
	}
	return true
}
